package org.jeecg.modules.rental.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.rental.entity.RentalBankCard;
import org.jeecg.modules.rental.service.IRentalBankCardService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 银行卡信息表
 * @Author: jeecg-boot
 * @Date:   2025-03-01
 * @Version: V1.0
 */
@Api(tags="银行卡信息表")
@RestController
@RequestMapping("/rental/rentalBankCard")
@Slf4j
public class RentalBankCardController extends JeecgController<RentalBankCard, IRentalBankCardService> {
	@Autowired
	private IRentalBankCardService rentalBankCardService;
	
	/**
	 * 分页列表查询
	 *
	 * @param rentalBankCard
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "银行卡信息表-分页列表查询")
	@ApiOperation(value="银行卡信息表-分页列表查询", notes="银行卡信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<RentalBankCard>> queryPageList(RentalBankCard rentalBankCard,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<RentalBankCard> queryWrapper = QueryGenerator.initQueryWrapper(rentalBankCard, req.getParameterMap());
		Page<RentalBankCard> page = new Page<RentalBankCard>(pageNo, pageSize);
		IPage<RentalBankCard> pageList = rentalBankCardService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param rentalBankCard
	 * @return
	 */
	@AutoLog(value = "银行卡信息表-添加")
	@ApiOperation(value="银行卡信息表-添加", notes="银行卡信息表-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:rental_bank_card:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody RentalBankCard rentalBankCard) {
		rentalBankCardService.save(rentalBankCard);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param rentalBankCard
	 * @return
	 */
	@AutoLog(value = "银行卡信息表-编辑")
	@ApiOperation(value="银行卡信息表-编辑", notes="银行卡信息表-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:rental_bank_card:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody RentalBankCard rentalBankCard) {
		rentalBankCardService.updateById(rentalBankCard);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "银行卡信息表-通过id删除")
	@ApiOperation(value="银行卡信息表-通过id删除", notes="银行卡信息表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:rental_bank_card:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		rentalBankCardService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "银行卡信息表-批量删除")
	@ApiOperation(value="银行卡信息表-批量删除", notes="银行卡信息表-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:rental_bank_card:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.rentalBankCardService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "银行卡信息表-通过id查询")
	@ApiOperation(value="银行卡信息表-通过id查询", notes="银行卡信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<RentalBankCard> queryById(@RequestParam(name="id",required=true) String id) {
		RentalBankCard rentalBankCard = rentalBankCardService.getById(id);
		if(rentalBankCard==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(rentalBankCard);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param rentalBankCard
    */
    //@RequiresPermissions("org.jeecg.modules.demo:rental_bank_card:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RentalBankCard rentalBankCard) {
        return super.exportXls(request, rentalBankCard, RentalBankCard.class, "银行卡信息表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("rental_bank_card:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RentalBankCard.class);
    }


	 @PostMapping("/addCard")
	 public Result<String> addBankCard(@RequestBody RentalBankCard rentalBankCard) {
		 try {
			 if (!isValidBankCard(rentalBankCard.getCardCode())) {
				 return Result.error("新增失败：无效的银行卡号！");
			 }
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 rentalBankCard.setOwnerId(sysUser.getId());
			 rentalBankCardService.save(rentalBankCard);
			 return Result.OK("添加成功！");
		 } catch (Exception e) {
			 return Result.error("添加失败：" + e.getMessage());
		 }
	 }

	 @PostMapping("/editCard")
	 public Result<String> editBankCard(@RequestBody RentalBankCard rentalBankCard) {
		 try {
			 // 验证银行卡号是否合法
			 if (!isValidBankCard(rentalBankCard.getCardCode())) {
				 rentalBankCard.setCardCode(null);
			 }

			 // 执行更新操作
			 rentalBankCardService.updateById(rentalBankCard);
			 return Result.OK("编辑成功！");
		 } catch (Exception e) {
			 return Result.error("编辑失败：" + e.getMessage());
		 }
	 }

	 @DeleteMapping("/deleteCard")
	 public Result<String> deleteBankCard(@RequestParam String id) {
		 try {
			 rentalBankCardService.removeById(id);
			 return Result.OK("删除成功！");
		 } catch (Exception e) {
			 return Result.error("删除失败：" + e.getMessage());
		 }
	 }
	 @GetMapping("/listCard")
	 public Result<List<RentalBankCard>> listBankCards() {
		 try {
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 String ownerId=sysUser.getId();
			 // 查询银行卡记录，加入 ownerId 条件
			 QueryWrapper<RentalBankCard> queryWrapper = new QueryWrapper<>();
			 queryWrapper.eq("owner_id", ownerId); // 添加 ownerId 查询条件

			 // 查询所有符合条件的记录
			 List<RentalBankCard> bankCards = rentalBankCardService.list(queryWrapper);

			 // 对查询结果中的卡号进行处理，保留后 5 位
			 List<RentalBankCard> filteredRecords = bankCards.stream().map(card -> {
				 String cardCode = maskCardCode(card.getCardCode()); // 对卡号进行掩码处理
				 card.setCardCode(cardCode);
				 return card;
			 }).collect(Collectors.toList());

			 return Result.OK(filteredRecords);
		 } catch (Exception e) {
			 return Result.error("获取列表失败：" + e.getMessage());
		 }
	 }

	 private String maskCardCode(String cardCode) {
		 if (cardCode == null) {
			 return null;
		 }
		 int length = cardCode.length();
		 if (length > 5) {
			 // 使用 StringBuilder 手动拼接
			 StringBuilder masked = new StringBuilder();
			 for (int i = 0; i < length - 5; i++) {
				 masked.append("*");
			 }
			 masked.append(cardCode.substring(length - 5));
			 return masked.toString();
		 } else {
			 // 如果卡号长度小于等于 5，全部用 "*" 替代
			 StringBuilder masked = new StringBuilder();
			 for (int i = 0; i < length; i++) {
				 masked.append("*");
			 }
			 return masked.toString();
		 }
	 }

	 private boolean isValidBankCard(String cardCode) {
		 // 判断银行卡号是否为空
		 if (cardCode == null || cardCode.trim().isEmpty()) {
			 return false;
		 }

		 // 检查是否为纯数字
		 if (!cardCode.matches("\\d+")) {
			 return false;
		 }

		 // 银行卡号长度通常在 16 到 19 位之间
		 if (cardCode.length() < 16 || cardCode.length() > 19) {
			 return false;
		 }

		 // Luhn 校验算法验证银行卡号
		 return validateLuhn(cardCode);
	 }

	 /**
	  * 使用 Luhn 算法验证银行卡号
	  * @param cardCode 银行卡号
	  * @return 是否通过验证
	  */
	 private boolean validateLuhn(String cardCode) {
		 int sum = 0;
		 boolean alternate = false;
		 for (int i = cardCode.length() - 1; i >= 0; i--) {
			 int digit = Character.getNumericValue(cardCode.charAt(i));
			 if (alternate) {
				 digit *= 2;
				 if (digit > 9) {
					 digit -= 9;
				 }
			 }
			 sum += digit;
			 alternate = !alternate;
		 }
		 return (sum % 10 == 0);
	 }

 }
